package com.netspider.utils;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Log
{
	public static void init()
	{
		log = Logger.getLogger(LOG_TAG);
		try
		{
			File log_folder = new File(LOG_PATH);
			if(!log_folder.exists())
			{
				log.log(Level.INFO, "the log path [" + LOG_PATH + "]" + " is not exist just create it");
				log_folder.mkdirs();
			}
			Calendar now = new GregorianCalendar(new SimpleTimeZone(1000*3600*8, "beijing"));
			String today = String.format("%d_%02d_%02d_%02d_%02d_%02d", now.get(Calendar.YEAR), now.get(Calendar.MONTH)+1, now.get(Calendar.DAY_OF_MONTH), 
				    				now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
			String logFilePath = String.format(LOG_PATH + LOG_FILENAME, today);
			File log_file = new File(logFilePath);
			if(!log_file.exists())
			{
				log_file.createNewFile();
			}
			
			FileHandler fh = new FileHandler(logFilePath);
			fh.setFormatter(new SimpleFormatter());
			log.addHandler(fh);
		}
		catch (SecurityException e)
		{
			log.log(Level.SEVERE, "can not access " + LOG_PATH, e);
		}
		catch (IOException e)
		{
			log.log(Level.SEVERE, "IO Exception when access log file", e);
		}	
		
		String log_level = Prop.getProp().getProperty(LOG_PROP);
		if(log_level.equals(LOG_PROP_ALL))
		{
			log.setLevel(Level.ALL);
		}
		else if(log_level.equals(LOG_PROP_FINE))
		{
			log.setLevel(Level.FINE);
		}
		else if(log_level.equals(LOG_PROP_INFO))
		{
			log.setLevel(Level.INFO);
		}
		else if(log_level.equals(LOG_PROP_WARNING))
		{
			log.setLevel(Level.WARNING);
		}
		else if(log_level.equals(LOG_PROP_SEVERE))
		{
			log.setLevel(Level.SEVERE);
		}
		else if(log_level.equals(LOG_PROP_OFF))
		{
			log.setLevel(Level.OFF);
		}
		else
		{
			log.setLevel(Level.OFF);
		}
	}
	public static Logger getLogger()
	{
		return log;
	}
	
	public static void test()
	{
		init();
		Logger log = getLogger();
		log.severe("test123456789");
	}
	
	
	private static Logger log;
	
	private static String LOG_FILENAME = "netspider_%s.log";
	private static final String LOG_PATH = "./log/";
	private static final String LOG_TAG = "netspider";
	private static final String LOG_PROP = "ro.Log.Level";
	
	private static final String LOG_PROP_ALL = "ALL";
	private static final String LOG_PROP_OFF = "OFF";
	private static final String LOG_PROP_FINE = "FINE";
	private static final String LOG_PROP_INFO = "INFO";
	private static final String LOG_PROP_WARNING = "WARNING";
	private static final String LOG_PROP_SEVERE = "SEVERE";
}
